use clap::{Arg, ArgAction, ArgMatches, Command};

use crate::environment::environment;

pub(super) const NAME: &'static str = "set";

pub(super) fn new() -> Command {
    let mut command = Command::new(NAME).about("设置环境变量");
    command = command.arg(Arg::new("name").required(true).help("工具名称"));
    command = command.arg(Arg::new("kvs").action(ArgAction::Append).required(true).help("键值对，最少一对，可以指定多个，样例: Key=Value [Key=Value] [Key=Value]"));

    command
}

pub(super) fn action(args: &ArgMatches) {
    let name = args.get_one::<String>("name").unwrap();
    let kvs: Vec<&String> = args.get_many::<String>("kvs").unwrap().into_iter().collect();

    for kv in kvs.into_iter() {
        let tokens: Vec<&str> = kv.splitn(2, "=").collect();
        if 2 != tokens.len() {
            continue;
        }

        let result = environment::global_mut().set_environment(name.as_str(), tokens[0].to_string(), tokens[1].to_string());
        if result.is_err() {
            println!("设置环境变量失败: {}", result.unwrap_err());
        }
    }
}